Passed
Push — develop ( c592f3...b91919 )
by Endre
04:18
created

Registry.attachAdapter   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
import ListenerAdapter from '../Observer/ListenerAdapter';
2
import {IObserver} from '../Observer/Observer';
3
import {IPageData} from './Router';
4
5
interface IRegistryPageData {
6
  page: IPageData,
7
  sourceUrl: string,
8
}
9
10
export interface IPageDictionary<T> {
11
  [index: string]: T
12
}
13
14
export default class Registry {
15
  dictionary: IPageDictionary<IRegistryPageData>;
16
  observer: IObserver<IPageData | null>;
17
18
  constructor(observer: IObserver<IPageData | null>) {
19 6
    this.observer = observer;
20 6
    this.dictionary = {};
21
  }
22
23
  attachAdapter(adapter: ListenerAdapter<IPageData>): void {
24 2
    adapter.addListener(this.updatePageData.bind(this));
25
  }
26
27
  getPages(): IPageDictionary<IPageData> {
28 2
    const pages: IPageDictionary<IPageData> = {};
29
30 2
    Object.keys(this.dictionary).forEach((pageName: string) => {
31 2
      const registeredPage: IRegistryPageData = this.dictionary[pageName];
32 2
      const page: IPageData = registeredPage.page;
33 2
      pages[page.name] = page;
34
    });
35
36 2
    return pages;
37
  }
38
39
  registerPage(page: IPageData) {
40 4
    const registeredPage: IRegistryPageData = {
41
      page: page,
42
      sourceUrl: page.url
43
    };
44
45 4
    if (this.observer.value != null) {
46 3
      this.updatePageUrlByDepth(registeredPage, this.observer.value.depth, false);
47
    }
48 4
    this.dictionary[page.name] = registeredPage;
49
  }
50
51
  protected updatePageData(newValue: IPageData): void {
52 2
    Object.keys(this.dictionary).forEach(
53
      (pageName: string) => {
54 4
        this.updatePageUrlByDepth(this.dictionary[pageName], newValue.depth, newValue.name == pageName);
55
      }
56
    );
57
  }
58
59
  protected updatePageUrlByDepth(registeredPage: IRegistryPageData, depth: number, removeDirectory: boolean): void {
60 7
    let relativeBack: string = '', index: number = 0, newUrl: string;
61
62 7
    if (removeDirectory) {
63 2
      newUrl = registeredPage.sourceUrl.replace(/.*\//, './');
64
    } else {
65 5
      for (index = 0; index < depth; index++) {
66 11
        relativeBack += '../';
67
      }
68 5
      newUrl = (relativeBack + registeredPage.sourceUrl).replace('.././', '../');
69
    }
70
71 7
    registeredPage.page.url = newUrl;
72
  }
73
}
74